cmake_minimum_required(VERSION  3.16.3)
project(libco)

include (cmake/utils.cmake)

# -fPIC: 生成位置无关的代码，便于动态链接
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")

set(CMAKE_CXX_FLAGS "$ENV{CXXFLAGS} -std=c++17 -O1 -ggdb -Wall -Winvalid-pch -fsanitize=address")
# set(CMAKE_CXX_FLAGS "$ENV{CXXFLAGS} -std=c++17 -O1 -ggdb -Wall -Winvalid-pch")

set(SRC_DIR "${CMAKE_SOURCE_DIR}/src")
include_directories("${PROJECT_SOURCE_DIR}/include/")

# 添加额外的库文件路径
link_directories("/usr/lib/x86_64-linux-gnu/")

# 查找 src 目录下的所有 .cpp 文件
file(GLOB SRC_FILES "${SRC_DIR}/*.cpp")

# 设置可执行文件输出路径
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin) 

# 创建动态库
add_library(libco SHARED ${SRC_FILES})

# 设置输出路径和动态库名
set_target_properties(libco PROPERTIES
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" OUTPUT_NAME "co"
)

#################################################### 生成测试文件 ########################################

# wrapper for add_executable
function(libco_add_executable targetname srcs)
    add_executable(${targetname} ${srcs})
    add_dependencies(${targetname} libco)
    target_link_libraries(${targetname} libco dl pthread)
endfunction()

# 测试目标名称
set(TARGETS
    # conqueue
    coroutine
    coroutine2
    cv
    log     
    mutex   
    thread
    processor
    monitor
    channel
    comutex
    startend
    hook
)

# 遍历每个目标和源文件路径，添加可执行文件
foreach(target_source ${TARGETS})
    list(GET target_source 0 target_name)

    set(source_file "test/test_${target_name}.cpp")

    # 检查测试cpp源文件是否存在
    if(NOT EXISTS "${CMAKE_SOURCE_DIR}/${source_file}")
        message(FATAL_ERROR "Source file ${source_file} does not exist.")
    endif()

    set(target_exec "test_${target_name}")

    # 添加可执行文件
    libco_add_executable(${target_exec} ${source_file})
endforeach()
